package org.snail.jobHierarchy.service.impl;

import lombok.extern.log4j.Log4j;
import org.snail.common.ExcelUtils;
import org.snail.constant.ErrCodeConstant;
import org.snail.exception.JobLevelException;
import org.snail.jobHierarchy.bean.JobDO;
import org.snail.jobHierarchy.mapper.JobsMapper;
import org.snail.jobHierarchy.service.JobsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Log4j
@Service
public class JobServiceImpl implements JobsService {
    @Autowired
    private JobsMapper jobsMapper;


    /**
     * 岗位层级报价已文件的形式保存到数据库
     * @param file     文件
     * @param request
     */
    @Override
    public void saveJobPrice(CommonsMultipartFile file, HttpServletRequest request) throws JobLevelException {
        List<JobDO> jobDOs = new ArrayList<>();
        jobDOs = ExcelUtils.getListFromExcel(file,getJobFilePath(file,request),JobDO.class,2);
        if(!checkJobExcel(jobDOs)){
            throw  new JobLevelException(ErrCodeConstant.JOBS_ERROR,"现场单价和外出单价必须只有一个有值");
        }
        try{
            jobsMapper.deleteAllJobs();
            jobsMapper.saveJobs(jobDOs);
        }catch (Exception e){
            log.error("保存到岗位层级单价异常:"+e.getMessage());
        }
    }


    /**
     * 岗位层级价格查询
     * 查询全部的数据
     * @return
     */
    @Override
    public List<JobDO> findAllJobPrice() {
        List<JobDO> jobDOs = null;
        try{
            jobDOs = jobsMapper.findAllJobPrice();
        }catch (Exception e){
            log.error("岗位层级单价查询失败:"+e.getMessage());
        }

        return jobDOs;
    }

    /**
     * 判断现场单价和外出单价异常情况
     * 只能有一个有值
     * @param jobDOs
     * @return
     */
    private boolean checkJobExcel(List<JobDO> jobDOs){
        boolean result = true;
        for(JobDO jobDO : jobDOs){
            if(jobDO.getNdc()==null&&jobDO.getOnSite()==null||jobDO.getNdc()!=null&&jobDO.getOnSite()!=null){
                return false;
            }
            jobDO.setCreateTime(new Date());
            jobDO.setIsDel(0);
        }
        return result;
    }
    //获取文件路径;
    private String getJobFilePath(CommonsMultipartFile file, HttpServletRequest request) {
        String excelName = file.getOriginalFilename();
        String outfileName = "out" + excelName;
        String pathHome = request.getSession().getServletContext().getRealPath("upload");
        String outfilePath = pathHome + "/" + outfileName;
        return outfilePath;
    }
}